package com.luge.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class StreamTool {
	
	public static void writeInputStream(File file, InputStream inputStream)
			throws IOException {
		OutputStream outputStream = new FileOutputStream(file);
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, len);
		}
		outputStream.flush();
		outputStream.close();
		inputStream.close();
		outputStream = null;
		inputStream = null;
	}

	public static boolean isConnect(String urlStr) {
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(5000);
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				return true;
			}
		} catch (IOException e) {
			return false;
		}
		return false;
	}

	public static InputStream getInputStream(String urlStr) throws Exception {
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.connect();
		conn.setReadTimeout(6000);
		return conn.getInputStream();
	}

	public static byte[] readInputStream(InputStream mInputStream)
			throws IOException {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream mOutputStream = new ByteArrayOutputStream();
		while ((len = mInputStream.read(buffer)) != -1) {
			mOutputStream.write(buffer, 0, len);
		}
		mOutputStream.close();
		mInputStream.close();
		return mOutputStream.toByteArray();
	}
}
